import { useEffect, useRef, useState } from 'react';
import { Card, Progress } from 'antd';
import { LoadingOutlined, CameraOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import { Notify, Toast, Dialog } from 'react-vant';
import { NavBar, Button } from 'react-vant';
import { Flex, Spin } from 'antd';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { LeftOutlined } from '@ant-design/icons'; // 导入 antd 的左箭头图标

function Face(props) {
    const [messageApi, contextHolder] = message.useMessage();
    let video = useRef(null);
    const navigate = useNavigate(); // 启用 useNavigate
    let canvas = useRef(null);
    let [imgSrc, setImgSrc] = useState('');
    const [isShow, setIsShow] = useState(false);
    const [faceStatus, setFaceStatus] = useState('开始拍摄');
    const [isLoadshow, setIsLoadshow] = useState(false);
    const [verificationState, setVerificationState] = useState('idle'); // idle | scanning | processing | success | fail
    const [progress, setProgress] = useState(0);
    const [stream, setStream] = useState(null); // 存储摄像头流，方便关闭
    const [showCaptureButton, setShowCaptureButton] = useState(false);
    const [hasVerifiedSuccess, setHasVerifiedSuccess] = useState(false); // 新增状态
    const [status, setStatus] = useState(''); // 新增状态
    const [backendData, setBackendData] = useState(null); // 新增状态
    const [ShowSuccessDialog, setShowSuccessDialog] = useState(false); // 新增状态
    const [isShow1,setisShow1]=useState(false); // 新增状态
    // 打开摄像头的方法
    const open = async () => {
        setIsShow(true);
        try {
            if (!navigator.mediaDevices) {
                navigator.mediaDevices = {};
            }
            if (!navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia = function (constraints) {
                    const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
                    if (!getUserMedia) {
                        return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                    }
                    return new Promise((resolve, reject) => {
                        getUserMedia.call(navigator, constraints, resolve, reject);
                    });
                };
            }
            const newStream = await navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false,
            });
            setStream(newStream);
            if (video.current) {
                video.current.srcObject = newStream;
                video.current.play();
            }
        } catch (err) {
            console.error('摄像头打开失败', err);
            Notify.show({ type: 'danger', message: '摄像头打开失败，请检查权限或设备' });
        }
    };

    // 关闭摄像头
    const close = () => {
        setIsShow(false);
        if (stream) {
            stream.getTracks().forEach(track => track.stop());
            setStream(null);
        }
    };

    // 截取视频画面  和人脸库对比人员信息
    const drawMedia = async () => {
        setVerificationState('processing');
        setProgress(0);
        const timer = setInterval(() => {
            setProgress(prev => {
                if (prev >= 100) {
                    clearInterval(timer);
                    return 100;
                }
                return prev + 10;
            });
        }, 300);
    
        try {
            if (!canvas.current || !video.current) throw new Error('Canvas或Video未初始化');
            const ctx = canvas.current.getContext('2d');
            if (!ctx) throw new Error('无法获取Canvas上下文');
    
            ctx.clearRect(0, 0, canvas.current.width, canvas.current.height);
            ctx.drawImage(
                video.current,
                (canvas.current.width - canvas.current.width * (320 / 240)) / 2,
                0,
                canvas.current.width * (320 / 240),
                canvas.current.height,
            );
    
            const base64 = canvas.current.toDataURL('image/jpeg');
            setImgSrc(base64);
    
            const { data } = await axios.post('http://localhost:3001/add-person', {
                imageBase64: base64.split(',')[1],
            }, { timeout: 5000 });
            console.log('收到后端响应:', data);
            setBackendData(data); // 保存后端返回的数据
    
            clearInterval(timer); // 确保在请求完成后清除定时器
            setProgress(100);
    
            // 输出code到控制台
            console.log('后端返回的code:', data.code);
    
            // 根据后端返回的code判断是否录入成功
            if (data.code === 0) {
                setIsLoadshow(false); // 关闭loading状态
                // setTimeout(()=>{
                    
                // },100)
                // 提示验证成功
                
                
                setTimeout(() => {
                    close(); // 关闭摄像头
                    setVerificationState('fail'); // 重置状态
                    setVerificationState('success'); // 修正为 success
                    // Notify.show({ type: 'success', message: '验证成功，人员录入完成' }); 
                    // alert("录入成功")
                    // navigate('/login'); // 跳转到登录页面
                }, 10000); // 1秒后关闭并跳转
            } else if (data.code === -1) {
                // 增加调试信息
                console.log('准备显示通知，code 为 -1'); 
                // 使用 setTimeout 延迟显示通知
                setTimeout(() => {
                    Notify.show({ type: 'danger', message: '录入失败：人脸信息不完整' });
                }, 0);
                setVerificationState('fail');
            } else if (data.code === -2) {
                Notify.show({ type: 'danger', message: '录入失败：人脸已存在' });
                setVerificationState('fail');
            } else {
                Notify.show({ type: 'danger', message: '录入失败：未知错误' });
                setVerificationState('fail');
            }
        } catch (error) {
            console.error('人脸识别录入失败', error);
            clearInterval(timer); // 确保在错误时清除定时器
            setProgress(100);
            Notify.show({ type: 'danger', message: '人脸录入失败，请重试' });
            setVerificationState('fail');
        }
    };

    const startVerification = () => {
        setVerificationState('scanning');
        open();
        setShowCaptureButton(true); // 显示立即拍摄按钮
    };

    const getVerificationContent = () => {
        if (hasVerifiedSuccess) {
            return null; // 如果已经验证成功过，直接返回 null
        }
        switch (verificationState) {
            case 'idle':
                return (
                    <div style={{ textAlign: 'center', padding: '4vw 0', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                        <CameraOutlined style={{ fontSize: '12vw', color: '#1890ff', marginBottom: '2vw' }} />
                        <p style={{ fontSize: '5vw', fontWeight: 'bold', marginBottom: '2vw' }}>请正对摄像头准备人脸录入</p>
                        <Button
                            type="primary"
                            size="normal"
                            onClick={startVerification}
                            className="face-verification-button"
                        >
                            开始录入
                        </Button>
                    </div>
                );
            case 'scanning':
                return (
                    <div style={{ textAlign: 'center', padding: '4vw 0' }}>
                        <p style={{ fontSize: '5vw', fontWeight: 'bold' }}>摄像头已打开，点击拍摄完成录入</p>
                    </div>
                );
            case 'processing':
                return (
                    <div style={{ textAlign: 'center', padding: '4vw 0', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                        {/* <Spin
                            indicator={<LoadingOutlined style={{ fontSize: '12vw', color: '#1890ff' }} spin />}
                        /> */}
                        <p style={{ fontSize: '5vw', fontWeight: 'bold', marginTop: '2vw' }}>
                            {verificationState === 'processing' && status== 0? '录入成功' : '正在录入人脸信息'}
                        </p>
                        <Progress
                            percent={progress}
                            status="active"
                            style={{ maxWidth: '70vw', width: '90%', marginTop: '2vw' }}
                        />
                        <Button type="primary" style={{ marginTop: "30px", width: "200px" }} onClick={()=>navigate('/login')}>返回登录</Button>
                    </div>
                );
            case 'success':
                setHasVerifiedSuccess(true); // 标记为已验证成功
                return (
                    <div style={{ textAlign: 'center', padding: '4vw 0', color: '#52c41a', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                        <CheckCircleOutlined style={{ fontSize: '16vw', marginBottom: '2vw' }} />
                        <p style={{ fontSize: '6vw', fontWeight: 'bold', marginBottom: '1vw' }}>录入成功</p>
                        <p style={{ fontSize: '5vw', marginBottom: '2vw' }}>人脸录入匹配成功</p>
                        <Button
                            type="primary"
                            size="large"
                            onClick={() => {
                                setVerificationState('idle');
                                close();
                            }}
                            style={{ width: '30vw', fontSize: '3vw' }}
                        >
                            返回
                        </Button>
                    </div>
                );
            case 'fail':
                return (
                    <div style={{ textAlign: 'center', padding: '4vw 0', color: '#f5222d', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                       111
                    </div>
                );
            default:
                return null;
        }
    };

    useEffect(() => {
        return () => {
            close(); // 组件卸载时关闭摄像头
        };
    }, []);

    return (
        <div>
            <NavBar
                title="人脸录入"
                leftText="返回"
                onClickLeft={()=>navigate(-1)}
                leftArrow={<LeftOutlined style={{ color: 'black' }} />}
                // 使用处理后的handleClose
                style={{ width: "100%", height: "50px", color: "black" }}
            />
            {isLoadshow ? <Spin indicator={<LoadingOutlined style={{ fontSize: '10vw' }} spin />} /> : null}
            <div style={{ maxWidth: '95vw', margin: '0 auto', padding: '5vw' }}>
                <canvas style={{ display: "none" }} ref={canvas} width="300" height="300"></canvas>
                <div style={{
                    display: isShow ? 'flex' : 'none',
                    justifyContent: 'center',
                    alignItems: 'center',
                    height: '40vh',
                    marginTop: '4vh'
                }}>
                    <video
                        ref={video}
                        preload="auto"
                        autoPlay
                        loop
                        muted
                        style={{
                            width: '6rem',
                            height: '6rem',
                            borderRadius: "50%",
                            objectFit: "cover",
                        }}
                    />
                </div>
                {getVerificationContent()}
                {showCaptureButton && verificationState === 'scanning' && (
                    <Button
                        type="primary"
                        size="large"
                        onClick={drawMedia}
                        style={{ width: '30vw', fontSize: '3vw', marginTop: '2vw', display: 'block', margin: '0 auto' }}
                    >
                        立即拍摄
                    </Button>
                )}
            </div>
            <Dialog
                title="录入成功"
                content="人员已成功录入系统！"
                confirmButtonText="确定"
                onConfirm={() => setShowSuccessDialog(false)}
            />
        </div>
    );
}

export default Face;
